import json
import boto3
import requests
import sys

overridden_parameters = {
    "enableNotification": False
}

spider_url_map = {
    "CoreProductsBestSellers": "pt-spider-serverless-CoreProductsBestSellers-monitor-queue",
    "CoreProductsMostWishedFor": "pt-spider-serverless-CoreProductsMostWishedFor-monitor-queue",
    "CoreProductsGiftIdeas": "pt-spider-serverless-CoreProductsGiftIdeas-monitor-queue",
    "CoreProductsMoversAndShakers": "pt-spider-serverless-CoreProductsMoversAndShakers-monitor-queue",
    "CoreProductsNewReleases": "pt-spider-serverless-CoreProductsNewReleases-monitor-queue"
}


def log_spider_job(jobId):
    """
    Call the updateSpiderJob API in order to mark the spider job completed
    :param jobId: pass from the SQS
    :return:
    """
    url = 'https://api.amzn-plus.com/prod/analytics/jobs/updateSpiderJob?jobId={}&status=Successful'.format(jobId)
    requests.put(url)
    print('end')


def call_EMR(jobId):
    """
    Send a event to EventBridge in order to invoke the EMR
    :param jobId: pass from the SQS
    :return:
    """
    print('start call EMR')
    entries = [
        {
            "DetailType": "Spider State-change Notification",
            "Source": "pt.spider",
            "Detail": "{\"state\":\"COMPLETED\",\"metadata\":{\"name\":\"AllCoreProducts\"},\"payload\":{\"jobId\":\"%s\"}}" % jobId
        }
    ]
    print("putting success event to EventBus, event detail is {}...".format(entries))
    event_bridge_client = boto3.client('events')
    response = event_bridge_client.put_events(
        Entries=entries
    )
    print("put success event to EventBus")


def lambda_handler(event, context):
    """
    Monitor the Spider Queue.
    If both approximate_number_of_messages and approximate_number_of_messages_delayed are zero,
    1. log spider job to mark the spider job completed
    2. send a event to EventBridge to invoke EMR
    :param event:
    :param context:
    :return:
    """
    sqs_client = boto3.client('sqs')
    queue = sqs_client.get_queue_by_name(QueueName='pt-spider-serverless-CoreProductsBestSellers-monitor-queue')
    # queue = sqs.get_queue_by_name(QueueName='pt-spider-serverless-CoreProductsBestSellers-queue')

    # Process messages by printing out body and optional author name
    for message in queue.receive_messages():
        if message.body is not None:
            jobId = json.loads(message.body)['batchId']
            category_code = json.loads(message.body)['spiderDataCategoryCode']
            base_queue_url = "https://sqs.us-east-2.amazonaws.com/599885534814/%s"
            queue_url = base_queue_url % spider_url_map[category_code]
            sys.path.append('jobs/amazon')
            response = sqs_client.get_queue_attributes(QueueUrl=queue_url,
                                                       AttributeNames=['ApproximateNumberOfMessages',
                                                                       'ApproximateNumberOfMessagesDelayed'])
            if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
                approximate_number_of_messages = response.get("Attributes", dict()).get("ApproximateNumberOfMessages", None)
                approximate_number_of_messages_delayed = response.get("Attributes", dict())\
                    .get("ApproximateNumberOfMessagesDelayed", None)

                print("The attribute approximate_number_of_messages: {}.".format(approximate_number_of_messages))
                print("The attribute approximate_number_of_messages_delayed: {}.".format(approximate_number_of_messages_delayed))

                if approximate_number_of_messages == 0 and approximate_number_of_messages_delayed == 0:

                    # log spider job to mark the spider job completed
                    log_spider_job(jobId)

                    # send a event to EventBridge to invoke EMR
                    call_EMR(jobId)

    return {
        'statusCode': 200,
        'body': json.dumps("lambda testing")
    }
